package cn.tedu.dimanage.user.webapi.security;

import cn.tedu.dimanage.common.web.State;
import cn.tedu.dimanage.pojo.vo.UserDetailVO;
import cn.tedu.dimanage.user.webapi.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Classname: UserDetailsServiceImpl
 * @Author: bromide
 * @CreateTime: 2022/6/25--12:49
 * @Version: V1.0
 * @Description:
 * SpringSecurity 将会自动调用UserDetailsService的实现类
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("根据用户名查询尝试登陆的用户信息" + username);
        UserDetailVO userDetailVO = userMapper.getDetailsByUsername(username);
        System.out.println("通过持久层进行查询,结果=" + userDetailVO);
        if (userDetailVO == null){
            System.out.println("根据用户名没有查到有效的用户数据,将抛出异常");
            throw new BadCredentialsException("登陆失败,用户名不存在!");
        }
        System.out.println("查询到匹配的用户数据,需要将此数据转换为UserDetails并返回");
        // 这个里面放入角色信息,方便后面判断身份使用
        List<String> roleId = new ArrayList<>();
        roleId.add(userDetailVO.getRoleId()+"");
        UserDetails userDetails = User.builder()
                .username(userDetailVO.getUsername())
                .password(userDetailVO.getPassword())
                .accountExpired(false)   // 账号是否过期
                .accountLocked(false)  //账号是否锁定
                .disabled(userDetailVO.getIsEnable() != 1)   //账号是否禁用
                .credentialsExpired(false) //证书认证是否过期
                .authorities(roleId.toArray(new String[] {}))  //权限
                .build();
        System.out.println("转换得到UserDetails = " + userDetails);
        return userDetails;
    }
}
